﻿$.dynamicSubmit = function (url, datas) {

    var form = $('#dynamicForm');

    if (form.length <= 0) {
        form = $("<form>");
        form.attr('id', 'dynamicForm');
        form.attr('style', 'display:none');
        form.attr('target', '');
        form.attr('method', 'get');

        $('body').append(form);
    }

    form = $('#dynamicForm');
    form.attr('action', url);
    form.empty();

    if (datas && typeof (datas) == 'object') {
        for (var item in datas) {
            var $_input = $('<input>');
            $_input.attr('type', 'hidden');
            $_input.attr('name', item);
            $_input.val(datas[item]);

            $_input.appendTo(form);
        }
    }

    form.submit();
}

Ext.define("PSI.InConsignation.MainForm", {
    setUserName: function (userName) {
        this.userName = userName;
    },

    setPermission: function (permission) {
        this.permission = permission;
    },

    createToolButtons: function () {
        var me = this;

        var result = [];
        var p = me.permission;
        if (p.canEdit === "1") {
            result.push("-");
            result.push({ text: "新增进口委托", iconCls: "psi-button-add", handler: me.onAddInConsignation, scope: me });
            result.push("-");
            result.push({ text: "编辑进口委托", iconCls: "psi-button-edit", handler: me.onEditInConsignation, scope: me });
            result.push("-");
            result.push({ text: "删除进口委托", iconCls: "psi-button-delete", handler: me.onDeleteInConsignation, scope: me });
            result.push("-");
            result.push({ text: "导入进口委托", iconCls: "psi-button-excel", handler: me.onUpload, scope: me });
        }

        if (p.canConfirm === "1") {
            result.push("-");

            result.push({ text: "确认运输", iconCls: "psi-button-ok", handler: me.onMakePlan, scope: me });
            result.push("-");

            result.push({ text: "取消运输", iconCls: "psi-button-cancel", handler: me.onCancelPlan, scope: me });
        }

        result.push("-");
        result.push({ text: "查看计划执行情况", iconCls: "psi-button-application_view_detail", handler: me.onViewPlan, scope: me });

        result.push("-");
        result.push({ text: "刷新", iconCls: "psi-button-refresh", handler: function () { me.refreshInConsignationGrid(); }, scope: me });
        result.push("-");
        result.push({
            text: "关闭", iconCls: "psi-button-exit", handler: function () {
                location.replace("/");
            }
        });

        return result;
    },

    createSubGridToolButtons: function () {
        var me = this;

        var p = me.permission;

        if (p.canEdit === "1") {
            return [
                "-",
                { text: "新增送货明细", iconCls: "psi-button-add", handler: me.onAddInConsignationDetail, scope: me },
                "-",
                { text: "编辑送货明细", iconCls: "psi-button-edit", handler: me.onEditInConsignationDetail, scope: me },
                "-",
                { text: "删除送货明细", iconCls: "psi-button-delete", handler: me.onDeleteInConsignationDetail, scope: me }
                //"-",
                //{ text: "费用", iconCls: "psi-button-money-yen", handler: me.onFee, scope: me },
                //"-",
                //{ text: "导出PDF", iconCls: "psi-button-add",handler:me.onMakePDF,scope:me }
            ];
        } else {
            return null;
        }
    },

    createUI: function () {
        var me = this;
        var panel = Ext.create("Ext.panel.Panel", {
            border: 0,
            layout: "border",
            title: "进口委托",
            tbar: me.createToolButtons(),
            items: [{
                region: "north",
                height: 40,
                layout: {
                    type: "table",
                    columns: 8
                },
                items: [
                    {
                        xtype: "label", text: "委托单号"
                    }, {
                        xtype: "textfield",
                        id: "editBillNumberQC",
                        width: 170,
                        margin: "4 5 0 5"
                    }, {
                        xtype: "label",
                        text: "接单日期"
                    }, {
                        xtype: "datefield",
                        margin: "4 5 0 5",
                        format: "Y-m-d",
                        width: 170,
                        id: "editDT1QC",
                        value: Ext.Date.add(new Date(), Ext.Date.DAY, -3)
                    }, {
                        xtype: "label",
                        text: "----"
                    }, {
                        xtype: "datefield",
                        margin: "4 5 0 5",
                        format: "Y-m-d",
                        width: 170,
                        id: "editDT2QC",
                        value: new Date()
                    }, {
                        xtype: "container",
                        border: 0,
                        width: 220,
                        layout: "hbox",
                        items: [
                            {
                                xtype: "button",
                                text: "查询",
                                iconCls: "psi-button-refresh",
                                margin: "4 5 0 5",
                                width: 90,
                                handler: function () { me.refreshInConsignationGrid(); },
                                scope: me
                            }, {
                                xtype: "button",
                                text: "清空查询条件",
                                margin: "4 5 0 5",
                                handler: me.onClearQC,
                                scope: me
                            }
                        ],
                        colspan: 2
                    }
                ]
            }, {
                region: "center", xtype: "container", layout: "fit", border: false,
                items: [me.getInConsignationGrid()]
            }, {
                id: "panelGoods",
                xtype: "panel",
                title: "送货明细",
                region: "south", xtype: "container", layout: "border", split: true,
                height: "60%",
                items: [{
                    xtype: "container", border: false,
                    region: "center",
                    layout: "fit",
                    items: [me.getInConsignationDetailGrid()]
                }, {
                    border: false,
                    xtype: "container",
                    region: "south",
                    height: 30,
                    items: [
                        {
                            xtype: "displayfield",
                            id: "editConsignationDetailInfo",
                            value: ""
                        }
                    ]
                }]
            }
            ]
        });

        me.panel = panel;

        var grid = me.getInConsignationGrid();
        var p = me.permission;
        if (p.canEdit === "1") {
            grid.on("itemdblclick", me.onEditInConsignation, me);
            me.getInConsignationDetailGrid().on("itemdblclick", me.onEditInConsignationDetail, me);
        }
        grid.on("selectionchange", me.refreshInConsignationDetailGrid, me);
    },

    getMainPanel: function () {
        return this.panel;
  
    },


    getInConsignationGrid: function () {
        var me = this;

        if (!me.__inConsignationGrid) {
            me.__inConsignationGrid = me.createInConsignationGrid();
        }

        return me.__inConsignationGrid;
    },

    getInConsignationDetailGrid: function () {
        var me = this;
        if (!me.__inConsignationDetailGrid) {
            me.__inConsignationDetailGrid = me.createInConsignationDetailGrid();
        }

        return me.__inConsignationDetailGrid;
    },

    getPanelGoods: function () {
        var me = this;
        if (!me.__panleGoods) {
            me.__panelGoods = Ext.getCmp("panelGoods");
        }

        return me.__panelGoods;
    },

    createInConsignationGrid: function () {
        var modelName = "PSIInConsignationModel";
        Ext.define(modelName, {
            extend: "Ext.data.Model",
            fields: ["id", "billNumber", "vsl", "voyNumber", "deliverDT", "clients", "bizMan", "bizDT", "status",
                "confirmUserName", "confirmDT", "actionDT", "cnt", "Cnt_ower", "Cnt_type", "goods"]
        });

        return Ext.create("Ext.grid.Panel", {
            viewConfig: { enableTextSelection: true },
            columnLines: true,
            border: 0,
            columns: [
                    Ext.create("Ext.grid.RowNumberer", { text: "", width: 30 }),
                    { header: "委托状态", dataIndex: "status", menuDisabled: true, width: 80 },
                    { header: "委托单号", dataIndex: "billNumber", menuDisabled: true },
                    { header: "船名/航次", dataIndex: "vsl", menuDisabled: true, width: 120 },
                    
                    { header: "箱属", dataIndex: "Cnt_ower", menuDisabled: true, width: 80 },
                    { header: "箱型", dataIndex: "Cnt_type", menuDisabled: true, width: 80 },
                    { header: "箱量", dataIndex: "cnt", menuDisabled: true, width: 80 },
                    { header: "货名", dataIndex: "goods", menuDisabled: true, width: 120 },
                    { header: "委托方", dataIndex: "clients", menuDisabled: true, width: 150 },
                    { header: "送货时限", dataIndex: "deliverDT", menuDisabled: true, width: 120 },
                    { header: "业务员", dataIndex: "bizMan", menuDisabled: true, width: 60 },
                    { header: "接单日期", dataIndex: "bizDT", menuDisabled: true, width: 80 },
                    { header: "确认运输人", dataIndex: "confirmUserName", menuDisabled: true, width: 80 },
                    { header: "确认运输时间", dataIndex: "confirmDT", menuDisabled: true, width: 120 },
                    { header: "计划执行日期", dataIndex: "actionDT", menuDisabled: true}
            ],
            store: Ext.create("Ext.data.Store", {
                autoLoad: false,
                model: modelName,
                data: []
            })
        });
    },

    createInConsignationDetailGrid: function () {
        var me = this;
        var modelName = "PSIInConsignationDetailModel";
        Ext.define(modelName, {
            extend: "Ext.data.Model",
            fields: ["id", "blNumber", "cntOwner", "cntType", "cntNumber", "address", "goodsOwner",
                "goodsOwnerTel", "unloadMan", "unloadManTel",
                 "memo", "goods", "status"
            ]
        });

        return Ext.create("Ext.grid.Panel", {
            viewConfig: { enableTextSelection: true },
            columnLines: true,
            tbar: me.createSubGridToolButtons(),
            columns: [
                    Ext.create("Ext.grid.RowNumberer", { text: "", width: 30 }),
                    { header: "状态", dataIndex: "status", menuDisabled: true },
                    { header: "运单号", dataIndex: "blNumber", menuDisabled: true },
                    { header: "箱属", dataIndex: "cntOwner", menuDisabled: true },
                    { header: "箱型", dataIndex: "cntType", menuDisabled: true },
                    { header: "箱号/封号", dataIndex: "cntNumber", menuDisabled: true, width: 250 },
                    { header: "门点", dataIndex: "address", menuDisabled: true },
                    { header: "货名", dataIndex: "goods", menuDisabled: true },
                    { header: "货主", dataIndex: "goodsOwner", menuDisabled: true },
                    { header: "货主电话", dataIndex: "goodsOwnerTel", menuDisabled: true },
                    { header: "卸货联系人", dataIndex: "unloadMan", menuDisabled: true },
                    { header: "卸货联系人电话", dataIndex: "unloadManTel", menuDisabled: true },
                    { header: "备注", dataIndex: "memo", menuDisabled: true}
            ],
            selModel: Ext.create("Ext.selection.CheckboxModel"),
            store: Ext.create("Ext.data.Store", {
                autoLoad: false,
                model: modelName,
                data: []
            })
        });
    },

    refreshInConsignationGrid: function (selectedId) {
        var me = this;

        me.getInConsignationDetailGrid().getStore().removeAll();

        var params = {
            billNumber: Ext.getCmp("editBillNumberQC").getValue(),
            dt1: Ext.getCmp("editDT1QC").getValue(),
            dt2: Ext.getCmp("editDT2QC").getValue()
        };

        var grid = me.getInConsignationGrid();
        var store = grid.getStore();
        var items = grid.getSelectionModel().getSelection();
        if (selectedId == null && items && items.length > 0) {
            selectedId = items[0].getData().id;
        }
        var el = grid.getEl() || Ext.getBody();
        el.mask("数据加载中...");
        Ext.Ajax.request({
            url: "/InConsignation/GetInConsignationListData",
            params: params,
            method: "POST",
            callback: function (options, success, response) {
                store.removeAll();

                if (success) {
                    var data = Ext.JSON.decode(response.responseText);
                    store.add(data);

                    if (selectedId) {
                        var bFound = false;
                        for (var i = 0; i < store.getCount() ; i++) {
                            var m = store.getAt(i);
                            if (m.get("id") == selectedId) {
                                bFound = true;
                                grid.getSelectionModel().select(m);
                                break;
                            }
                        }
                        if (!bFound && data.length > 0) {
                            grid.getSelectionModel().select(0);
                        }
                    } else {
                        if (data.length > 0) {
                            grid.getSelectionModel().select(0);
                        }
                    }
                } else {
                    PSI.MsgBox.showInfo("网络错误");
                }

                el.unmask();
            }
        });
    },

    refreshInConsignationDetailGrid: function () {
        var me = this;

        var parentGrid = me.getInConsignationGrid();
        var parentItems = parentGrid.getSelectionModel().getSelection();
        if (!parentItems || parentItems.length == 0) {
            return;
        }

        var parentEntity = parentItems[0].getData();
        me.getInConsignationDetailGrid().setTitle("进口委托[" + parentEntity.billNumber + "]的送货明细");
        var parentId = parentEntity.id;

        var grid = me.getInConsignationDetailGrid();
        var store = grid.getStore();

        var items = grid.getSelectionModel().getSelection();
        var selectedId = null;
        if (items && items.length > 0) {
            selectedId = items[0].getData().id;
        }

        var el = grid.getEl() 
        el.mask("数据加载中...");
        Ext.Ajax.request({
            url: "/InConsignation/GetInConsignationDetailListData",
            params: { id: parentId },
            method: "POST",
            callback: function (options, success, response) {
                store.removeAll();

                if (success) {
                    var data = Ext.JSON.decode(response.responseText);
                    store.add(data);

                    if (selectedId) {
                        for (var i = 0; i < store.getCount() ; i++) {
                            var m = store.getAt(i);
                            if (m.get("id") == selectedId) {
                                grid.getSelectionModel().select(m);
                                break;
                            }
                        }
                    }

                    var info = "进口委托[" + parentEntity.billNumber + "]共有<span style='color:red'>"
                        + data.length + "</span>条送货明细";
                    Ext.getCmp("editConsignationDetailInfo").setValue(info);
                } else {
                    PSI.MsgBox.showInfo("网络错误");
                }

                el.unmask();
            }
        });

    },

    onAddInConsignation: function () {
        Ext.getCmp("editBillNumberQC").setValue(null);

        var form = Ext.create("PSI.InConsignation.ConsignationEditForm");
        form.show(this);
    },

    onEditInConsignation: function () {
        var me = this;
        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (!items || items.length != 1) {
            PSI.MsgBox.showInfo("请选择一个要编辑的进口委托");
            return;
        }

        var form = Ext.create("PSI.InConsignation.ConsignationEditForm");
        form.show(me, items[0].getData());
    },

    onDeleteInConsignation: function () {
        var me = this;
        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (!items || items.length == 0) {
            PSI.MsgBox.showInfo("请选择要删除的进口委托");
            return;
        }
        var info = "请确认是否删除选中的进口委托?";


        PSI.MsgBox.confirm(info, function () {
            var idList = [];
            for (var i = 0; i < items.length; i++) {
                var data = items[i].getData();
                idList.push(data.id);
            }
            var idListJson = Ext.JSON.encode(idList);
            var el = Ext.getBody();
            el.mask("正在删除中...");
            Ext.Ajax.request({
                url: "/InConsignation/DeleteInConsignation",
                method: "POST",
                params: { id: idListJson },
                callback: function (options, success, response) {
                    el.unmask();

                    if (success) {
                        var data = Ext.JSON.decode(response.responseText);
                        if (data.success) {
                            PSI.MsgBox.showInfo("成功完成删除操作", function () {
                                me.refreshInConsignationGrid();
                            });
                        } else {
                            PSI.MsgBox.showInfo(data.msg);
                        }
                    } else {
                        PSI.MsgBox.showInfo("网络错误");
                    }
                }
            });

        });
    },

    onUpload: function () {
        var form = Ext.create("PSI.InConsignation.UploadForm");
        form.show(this);
    },

    onMakePlan: function () {
        var me = this;
        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (items == null || items.length != 1) {
            PSI.MsgBox.showInfo("请选择要一个要确认的进口委托");
            return;
        }
        var bill = items[0].getData();
        if (bill.status && bill.status != "") {
            PSI.MsgBox.showInfo("当前委托已经确认运输了");
            return;
        }
        var cnt = me.getInConsignationDetailGrid().getStore().getCount();
        if (cnt == 0) {
            PSI.MsgBox.showInfo("当前委托没有送货明细，不能确认运输");
            return;
        }
        var form = Ext.create("PSI.InConsignation.ConfirmForm");
        form.show(me, bill);
    },

    onCancelPlan: function () {
        var me = this;
        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (items == null || items.length != 1) {
            PSI.MsgBox.showInfo("请选择要一个要取消的进口委托");
            return;
        }
        var bill = items[0].getData();
        if (!bill.status) {
            PSI.MsgBox.showInfo("当前委托还没有被确认运输");
            return;
        }

        PSI.MsgBox.confirm("请确认是否取消运输?", function () {
            var el = Ext.getBody();
            el.mask("正在处理中...");
            Ext.Ajax.request({
                url: "/InConsignation/CancelPlan",
                method: "POST",
                params: { id: bill.id },
                callback: function (options, success, response) {
                    el.unmask();

                    if (success) {
                        var data = Ext.JSON.decode(response.responseText);
                        if (data.success) {
                            PSI.MsgBox.showInfo("成功取消运输", function () {
                                me.refreshInConsignationGrid();
                            });
                        } else {
                            PSI.MsgBox.showInfo(data.msg);
                        }
                    } else {
                        PSI.MsgBox.showInfo("网络错误");
                    }
                }
            });

        });
    },

    onViewPlan: function () {
        var me = this;
        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (items == null || items.length != 1) {
            PSI.MsgBox.showInfo("请选择一个进口委托");
            return;
        }
        var bill = items[0].getData();
        var status = bill.status;

        if (status == null || status == "") {
            PSI.MsgBox.showInfo("委托还没有确认运输，没有形成运输计划");

            return;
        }

        window.open("/InPlan/Index?billNumber=" + bill.billNumber);
    },

    onMakePDF:function(){
        var me = this;
        var items = me.getInConsignationDetailGrid().getSelectionModel().getSelection();
        if (!items || items.length != 1) {
            PSI.MsgBox.showInfo("请选择一个进口委托");
            return;
        }
        var cc = items[0].getData();

        $.dynamicSubmit("/InConsignation/MakePDF", { id: cc["id"] });
    
    },

    onAddInConsignationDetail: function () {
        var me = this;

        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (!items || items.length == 0) {
            PSI.MsgBox.showInfo("没有选择进口委托");
            return;
        }
        var c = items[0].getData();
        if (c.status != null && c.status != "") {
            PSI.MsgBox.showInfo("委托已经被确认运输，不能再新增送货明细");
            return;
        }

        var parentId = c.id;

        var form = Ext.create("PSI.InConsignation.ConsignationDetailEditForm");
        form.show(me, parentId);
    },

    onEditInConsignationDetail: function () {
        var me = this;

        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (!items || items.length == 0) {
            PSI.MsgBox.showInfo("没有选择进口委托");
            return;
        }

        var parentId = items[0].getData().id;
        var items = me.getInConsignationDetailGrid().getSelectionModel().getSelection();
        if (items == null || items.length != 1) {
            PSI.MsgBox.showInfo("请选择一条要编辑的送货明细记录");

            return;
        }

        var form = Ext.create("PSI.InConsignation.ConsignationDetailEditForm");
        form.show(me, parentId, items[0].getData());
    },

    onDeleteInConsignationDetail: function () {
        var me = this;

        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (!items || items.length == 0) {
            PSI.MsgBox.showInfo("没有选择进口委托");
            return;
        }

        var parentId = items[0].getData().id;
        var items = me.getInConsignationDetailGrid().getSelectionModel().getSelection();
        if (items == null || items.length == 0) {
            PSI.MsgBox.showInfo("请选择要删除的送货明细记录");

            return;
        }

        var info = "请确认是否删除选中的<span style='color:red'>" + items.length + "</span>个送货明细?";
        PSI.MsgBox.confirm(info, function () {
            var idList = [];
            for (var i = 0; i < items.length; i++) {
                var data = items[i].getData();
                idList.push(data.id);
            }
            var idListJson = Ext.JSON.encode(idList);
            var el = Ext.getBody();
            el.mask("正在删除中...");
            Ext.Ajax.request({
                url: "/InConsignation/DeleteInConsignationDetail",
                method: "POST",
                params: { id: idListJson, parentId: parentId },
                callback: function (options, success, response) {
                    el.unmask();

                    if (success) {
                        var data = Ext.JSON.decode(response.responseText);
                        if (data.success) {
                            PSI.MsgBox.showInfo("成功完成删除操作", function () {
                                me.refreshInConsignationDetailGrid();
                            });
                        } else {
                            PSI.MsgBox.showInfo(data.msg);
                        }
                    } else {
                        PSI.MsgBox.showInfo("网络错误");
                    }
                }
            });
        });
    },

    onFee: function () {
        var me = this;

        var items = me.getInConsignationGrid().getSelectionModel().getSelection();
        if (!items || items.length != 1) {
            PSI.MsgBox.showInfo("请选择一个进口委托");
            return;
        }
        var consignation = items[0].getData();

        var form = Ext.create("PSI.InConsignation.FeeMainForm");
        form.show(me, consignation.id);
    },

    onClearQC: function () {
        Ext.getCmp("editBillNumberQC").setValue(null);
        Ext.getCmp("editDT1QC").setValue(null);
        Ext.getCmp("editDT2QC").setValue(null);
    }
});
